package org.zoomdev.zoom.lock.modules;


import org.zoomdev.zoom.lock.LockFactory;
import org.zoomdev.zoom.lock.PoolException;

import java.util.concurrent.locks.Lock;

public class DefaultLockFactory extends DefaultKeyedObjectPool<Lock> implements LockFactory<Lock> {

    private final boolean fair;

    public DefaultLockFactory() {
        this(100);
    }

    public DefaultLockFactory(int maxTotal) {
        this(maxTotal, false);
    }

    public DefaultLockFactory(int maxTotal, boolean fair) {
        super(maxTotal);
        this.fair = fair;
    }

    @Override
    protected void initObject(Lock data, String key) {
        ((ProxyLock) data).setKey(key);
    }

    @Override
    protected Lock createObject(String key) {
        ProxyLock lock = new ProxyLock(this, fair);
        lock.setKey(key);
        return lock;
    }

    @Override
    protected Lock clearObject(Lock data, String key) {
        return data;
    }


    @Override
    public Lock tryFetch(String key) {
        try {
            return fetch(key);
        } catch (PoolException e) {
            return null;
        }

    }
}
